import random
from node import Node

class Tree:

    def __init__(self, root):
        self.root = root
        self.size = 0

    def setSize(self, size):
        self.size = size

    def getSize(self):
        return self.size

    def getRoot(self):
        return self.root

    def iterator(self, curr):
        if curr is not None:
            #print curr.getLabel()
            if curr.getChild1() is not None:
                for x in self.iterator(curr.getChild1()):
                    yield x
                    
            yield curr

            if curr.getChild2() is not None:
                for x in self.iterator(curr.getChild2()):
                    yield x

    def toString(self):
        print self.root.getChild1().getLabel()
        self.Children(self.root.getChild1(), 1)

    def Children(self, child, distance):
        if child.getChild1() is not None:
            self.Children(child.getChild1(), distance + 1)
            print ("    " * distance) + child.getChild1().getLabel()
        if child.getChild2() is not None:
            print ("    " * distance) + child.getChild2().getLabel()
            self.Children(child.getChild2(), distance + 1)

    def addChildRandom(self, symbol, size):
        count = 0
        location = random.randint(1, size)
        for node in self.iterator(self.root):
            count = count + 1
            if count == location:
                if node.getChild1() is None:
                    child = Node(symbol, node, style=Node.NORM)
                    node.setChild1(child)
                    child.setParent(node)
                elif node.getChild2() is None:
                    child = Node(symbol, node, style=Node.NORM)
                    node.setChild2(child)
                    child.setParent(node)
                else:
                    self.addChildRandom(symbol, size)
        
                    
